/**
 * @file snakegamewidget.cpp
 * @brief Snake游戏主界面窗口类实现文件
 *
 * 实现Snake游戏主界面的所有功能，包括：
 * - UI界面的创建和布局管理
 * - 游戏状态的显示和更新
 * - 用户交互的处理和响应
 * - 游戏控制和导航功能
 * - 聊天系统和社交功能
 */

#include "../include/snakegamewidget.h"
#include "../include/config.h"
#include <QDebug>               // 调试输出
#include <QMessageBox>          // 消息框
#include <QInputDialog>         // 输入对话框
#include <QKeyEvent>            // 键盘事件
#include <QCloseEvent>          // 关闭事件
#include <QShowEvent>           // 显示事件
#include <QHideEvent>           // 隐藏事件
#include <QApplication>         // 应用程序
#include <QDateTime>            // 时间处理
#include <QJsonDocument>        // JSON文档处理
#include <QSettings>            // 设置管理

/**
 * @brief SnakeGameWidget构造函数
 * @param parent 父窗口部件指针
 *
 * 初始化Snake游戏主界面：
 * 1. 创建核心组件
 * 2. 设置UI界面
 * 3. 建立信号槽连接
 * 4. 初始化状态
 */
SnakeGameWidget::SnakeGameWidget(QWidget *parent)
    : QWidget(parent)
    , m_gameManager(new SnakeGameManager(this))
    , m_gameRenderer(new SnakeGameRenderer(this))
    , m_singlePlayerWidget(nullptr)
    , m_mainLayout(nullptr)
    , m_stackedWidget(nullptr)
    , m_leftPanel(nullptr)
    , m_rightPanel(nullptr)
    , m_leftPanelLayout(nullptr)
    , m_leftLeftPanel(nullptr)
    , m_leftRightPanel(nullptr)
    , m_rightPanelLayout(nullptr)
    , m_rightTopPanel(nullptr)
    , m_rightMiddlePanel(nullptr)
    , m_rightBottomPanel(nullptr)
    , m_currentPage(LobbyPage)
    , m_statusUpdateTimer(new QTimer(this))
    , m_roomListRefreshTimer(new QTimer(this))
{
    // === 设置窗口属性 ===
    setWindowTitle("Snake Game");
    setMinimumSize(1000, 700);
    resize(1200, 800);
    
    // === 设置游戏渲染器 ===
    m_gameRenderer->setGameState(m_gameManager->getGameState());
    
    // === 设置UI界面 ===
    setupUI();
    
    // === 应用统一样式主题 ===
    applyUnifiedTheme();
    
    // === 建立信号槽连接 ===
    setupConnections();
    
    // === 设置定时器 ===
    m_statusUpdateTimer->setInterval(1000); // 每秒更新一次状态
    m_statusUpdateTimer->setSingleShot(false);
    connect(m_statusUpdateTimer, &QTimer::timeout,
            this, &SnakeGameWidget::onStatusUpdateTimer);
    m_statusUpdateTimer->start();
    
    m_roomListRefreshTimer->setInterval(30000); // 每30秒刷新一次房间列表
    m_roomListRefreshTimer->setSingleShot(false);
    connect(m_roomListRefreshTimer, &QTimer::timeout,
            this, &SnakeGameWidget::onRoomListRefreshTimer);
    
    // === 加载设置 ===
    loadSettings();
    
    qDebug() << "SnakeGameWidget initialized";
}

/**
 * @brief SnakeGameWidget析构函数
 */
SnakeGameWidget::~SnakeGameWidget()
{
    // === 保存设置 ===
    saveSettings();
    
    // === 断开游戏连接 ===
    if (m_gameManager->isConnectedToGame()) {
        m_gameManager->disconnectFromGameServer();
    }
    
    qDebug() << "SnakeGameWidget destroyed";
}

/**
 * @brief 初始化游戏界面
 * @param apiGatewayUrl API网关URL
 * @param accessToken 访问令牌
 * @param playerId 玩家ID
 * @param playerName 玩家名称
 */
void SnakeGameWidget::initialize(const QString &apiGatewayUrl, const QString &accessToken,
                                const QString &playerId, const QString &playerName)
{
    qDebug() << "Initializing SnakeGameWidget for player:" << playerName << "(" << playerId << ")";
    
    // === 初始化游戏管理器 ===
    m_gameManager->initialize(apiGatewayUrl, accessToken);
    m_gameManager->setPlayerInfo(playerId, playerName);
    
    // === 更新UI状态 ===
    updateConnectionStatus();
    
    qDebug() << "SnakeGameWidget initialization completed";
}

/**
 * @brief 显示游戏界面
 */
void SnakeGameWidget::showGame()
{
    show();
    raise();
    activateWindow();
    setFocus();
    
    // === 切换到大厅页面 ===
    switchToPage(LobbyPage);
    
    qDebug() << "Snake game interface shown";
}

/**
 * @brief 隐藏游戏界面
 */
void SnakeGameWidget::hideGame()
{
    hide();
    
    // === 如果在游戏中，先离开房间 ===
    if (isInGame()) {
        leaveGameRoom();
    }
    
    qDebug() << "Snake game interface hidden";
}

/**
 * @brief 切换到指定页面
 * @param page 目标页面
 */
void SnakeGameWidget::switchToPage(GamePage page)
{
    if (m_currentPage == page) {
        return;
    }
    
    m_currentPage = page;
    m_stackedWidget->setCurrentIndex(static_cast<int>(page));
    
    // === 根据页面更新状态 ===
    switch (page) {
    case LobbyPage:
        setWindowTitle("Snake Game - Lobby");
        m_roomListRefreshTimer->start();
        updateRoomList();
        break;
    case GamePage_Playing:
        setWindowTitle("Snake Game - Playing");
        m_roomListRefreshTimer->stop();
        updateGameInfo();
        break;
    case SinglePlayerPage:
        setWindowTitle("Snake Game - 单人模式");
        m_roomListRefreshTimer->stop();
        
        // === 停止主游戏渲染器，避免定时器冲突 ===
        if (m_gameRenderer) {
            qDebug() << "SnakeGameWidget: 停止主游戏渲染器";
            m_gameRenderer->setAnimationsEnabled(false);
        }
        
        // === 切换到单人游戏组件 ===
        if (m_singlePlayerWidget) {
            qDebug() << "SnakeGameWidget: 启动单人游戏模式";
            m_singlePlayerWidget->startGame();
        }
        break;
    case SettingsPage:
        setWindowTitle("Snake Game - Settings");
        m_roomListRefreshTimer->stop();
        break;
    case StatsPage:
        setWindowTitle("Snake Game - Statistics");
        m_roomListRefreshTimer->stop();
        updatePlayerStats();
        break;
    }
    
    qDebug() << "Switched to page:" << static_cast<int>(page);
}

/**
 * @brief 获取当前页面
 * @return 当前页面
 */
SnakeGameWidget::GamePage SnakeGameWidget::getCurrentPage() const
{
    return m_currentPage;
}

/**
 * @brief 连接到游戏服务器
 * @param region 首选地区
 */
void SnakeGameWidget::connectToGameServer(const QString &region)
{
    if (m_gameManager->getConnectionStatus() != SnakeGameManager::Disconnected) {
        qWarning() << "Already connected or connecting to game server";
        return;
    }
    
    qDebug() << "Connecting to game server, region:" << region;
    
    // === 更新UI状态 ===
    m_connectButton->setEnabled(false);
    m_connectButton->setText("Connecting...");
    m_connectionStatusLabel->setText("Connecting to game server...");
    
    // === 开始连接 ===
    m_gameManager->connectToGameServer(QString(), region);
}

/**
 * @brief 断开游戏服务器连接
 */
void SnakeGameWidget::disconnectFromGameServer()
{
    qDebug() << "Disconnecting from game server";
    
    // === 如果在游戏中，先离开房间 ===
    if (isInGame()) {
        leaveGameRoom();
    }
    
    // === 断开连接 ===
    m_gameManager->disconnectFromGameServer();
    
    // === 更新UI状态 ===
    updateConnectionStatus();
}

/**
 * @brief 创建游戏房间
 */
void SnakeGameWidget::createGameRoom()
{
    if (!isConnectedToGame()) {
        showErrorMessage("Error", "Not connected to game server");
        return;
    }

    // === 创建房间配置对话框 ===
    SnakeCreateRoomDialog dialog(this);

    // === 设置默认配置 ===
    SnakeGameManager::GameConfig defaultConfig;
    defaultConfig.roomName = QString("Room_%1").arg(QDateTime::currentSecsSinceEpoch());
    defaultConfig.maxPlayers = 4;
    defaultConfig.gameMode = 1;
    defaultConfig.mapWidth = 40;
    defaultConfig.mapHeight = 30;
    defaultConfig.gameSpeedMs = 100;
    defaultConfig.enableWalls = true;
    defaultConfig.enableSpecialFoods = false;
    defaultConfig.maxFoodCount = 10;

    dialog.setDefaultConfig(defaultConfig);

    // === 显示对话框 ===
    if (dialog.exec() == QDialog::Accepted) {
        SnakeGameManager::GameConfig config = dialog.getRoomConfig();

        qDebug() << "Creating room:" << config.roomName;

        // === 创建房间 ===
        m_gameManager->createRoom(config);

        // === 更新UI状态 ===
        m_createRoomButton->setEnabled(false);
        m_createRoomButton->setText("Creating...");
    }
}

/**
 * @brief 加入游戏房间
 * @param roomId 房间ID
 */
void SnakeGameWidget::joinGameRoom(const QString &roomId)
{
    if (!isConnectedToGame()) {
        showErrorMessage("Error", "Not connected to game server");
        return;
    }
    
    if (roomId.isEmpty()) {
        showErrorMessage("Error", "No room selected");
        return;
    }
    
    qDebug() << "Joining room:" << roomId;
    
    // === 加入房间 ===
    m_gameManager->joinRoom(roomId);
    
    // === 更新UI状态 ===
    m_joinRoomButton->setEnabled(false);
    m_joinRoomButton->setText("Joining...");
}

/**
 * @brief 离开游戏房间
 */
void SnakeGameWidget::leaveGameRoom()
{
    if (!isInGame()) {
        return;
    }
    
    qDebug() << "Leaving game room";
    
    // === 离开房间 ===
    m_gameManager->leaveRoom();
    
    // === 切换到大厅页面 ===
    switchToPage(LobbyPage);
}

/**
 * @brief 是否已连接到游戏
 * @return true表示已连接
 */
bool SnakeGameWidget::isConnectedToGame() const
{
    return m_gameManager->getConnectionStatus() == SnakeGameManager::InGame;
}

/**
 * @brief 是否在游戏中
 * @return true表示在游戏中
 */
bool SnakeGameWidget::isInGame() const
{
    return !m_currentRoomId.isEmpty() && isConnectedToGame();
}

/**
 * @brief 键盘按下事件处理
 * @param event 键盘事件
 */
void SnakeGameWidget::keyPressEvent(QKeyEvent *event)
{
    // === 游戏控制键处理 ===
    if (m_currentPage == GamePage_Playing && isInGame()) {
        switch (event->key()) {
        case Qt::Key_W:
        case Qt::Key_Up:
            m_gameManager->changeDirection(Direction::Up);
            event->accept();
            return;
        case Qt::Key_D:
        case Qt::Key_Right:
            m_gameManager->changeDirection(Direction::Right);
            event->accept();
            return;
        case Qt::Key_S:
        case Qt::Key_Down:
            m_gameManager->changeDirection(Direction::Down);
            event->accept();
            return;
        case Qt::Key_A:
        case Qt::Key_Left:
            m_gameManager->changeDirection(Direction::Left);
            event->accept();
            return;
        case Qt::Key_Escape:
            // 返回大厅
            switchToPage(LobbyPage);
            event->accept();
            return;
        }
    }

    // === 全局快捷键处理 ===
    switch (event->key()) {
    case Qt::Key_F1:
        switchToPage(LobbyPage);
        event->accept();
        return;
    case Qt::Key_F2:
        if (isInGame()) {
            switchToPage(GamePage_Playing);
        }
        event->accept();
        return;
    case Qt::Key_F3:
        switchToPage(SettingsPage);
        event->accept();
        return;
    case Qt::Key_F4:
        switchToPage(StatsPage);
        event->accept();
        return;
    }

    QWidget::keyPressEvent(event);
}

/**
 * @brief 键盘释放事件处理
 * @param event 键盘事件
 */
void SnakeGameWidget::keyReleaseEvent(QKeyEvent *event)
{
    QWidget::keyReleaseEvent(event);
}

/**
 * @brief 关闭事件处理
 * @param event 关闭事件
 */
void SnakeGameWidget::closeEvent(QCloseEvent *event)
{
    // === 如果在游戏中，询问是否确认关闭 ===
    if (isInGame()) {
        int ret = QMessageBox::question(this, "Confirm Close",
                                       "You are currently in a game. Are you sure you want to close?",
                                       QMessageBox::Yes | QMessageBox::No,
                                       QMessageBox::No);

        if (ret == QMessageBox::No) {
            event->ignore();
            return;
        }

        // === 离开游戏房间 ===
        leaveGameRoom();
    }

    // === 断开游戏连接 ===
    if (isConnectedToGame()) {
        disconnectFromGameServer();
    }

    // === 发送关闭信号 ===
    emit gameClosed();

    event->accept();
}

/**
 * @brief 显示事件处理
 * @param event 显示事件
 */
void SnakeGameWidget::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);

    // === 设置焦点以接收键盘事件 ===
    setFocus();

    // === 发送游戏状态改变信号 ===
    emit gameStateChanged(isConnectedToGame(), isInGame());
}

/**
 * @brief 隐藏事件处理
 * @param event 隐藏事件
 */
void SnakeGameWidget::hideEvent(QHideEvent *event)
{
    QWidget::hideEvent(event);

    // === 发送游戏状态改变信号 ===
    emit gameStateChanged(false, false);
}

/**
 * @brief 连接状态改变处理
 * @param status 连接状态
 */
void SnakeGameWidget::onConnectionStatusChanged(SnakeGameManager::ConnectionStatus status)
{
    qDebug() << "Connection status changed to:" << static_cast<int>(status);

    // === 更新连接状态显示 ===
    updateConnectionStatus();

    // === 根据状态更新UI ===
    switch (status) {
    case SnakeGameManager::Disconnected:
        m_connectButton->setEnabled(true);
        m_connectButton->setText("Connect");
        m_disconnectButton->setEnabled(false);
        m_createRoomButton->setEnabled(false);
        m_joinRoomButton->setEnabled(false);
        m_refreshRoomsButton->setEnabled(false);
        m_roomListWidget->clear();
        break;

    case SnakeGameManager::Connecting:
        m_connectButton->setEnabled(false);
        m_connectButton->setText("Connecting...");
        m_disconnectButton->setEnabled(false);
        break;

    case SnakeGameManager::Connected:
        m_connectButton->setEnabled(false);
        m_disconnectButton->setEnabled(true);
        break;

    case SnakeGameManager::InGame:
        m_connectButton->setEnabled(false);
        m_disconnectButton->setEnabled(true);
        m_createRoomButton->setEnabled(true);
        m_createRoomButton->setText("Create Room");
        m_joinRoomButton->setEnabled(true);
        m_joinRoomButton->setText("Join Room");
        m_refreshRoomsButton->setEnabled(true);

        // === 开始刷新房间列表 ===
        if (m_currentPage == LobbyPage) {
            m_roomListRefreshTimer->start();
            updateRoomList();
        }
        break;

    case SnakeGameManager::Error:
        m_connectButton->setEnabled(true);
        m_connectButton->setText("Connect");
        m_disconnectButton->setEnabled(false);
        m_createRoomButton->setEnabled(false);
        m_joinRoomButton->setEnabled(false);
        m_refreshRoomsButton->setEnabled(false);
        break;
    }

    // === 发送游戏状态改变信号 ===
    emit gameStateChanged(isConnectedToGame(), isInGame());
}

/**
 * @brief 游戏服务器列表获取处理
 * @param servers 服务器列表
 */
void SnakeGameWidget::onGameServersReceived(const QList<SnakeApiClient::GameServerInfo> &servers)
{
    qDebug() << "Received" << servers.size() << "game servers";

    // === 可以在这里显示服务器选择界面 ===
    // 目前自动选择推荐服务器
}

/**
 * @brief 游戏登录成功处理
 * @param loginResult 登录结果
 */
void SnakeGameWidget::onGameLoginSucceeded(const SnakeApiClient::GameLoginResult &loginResult)
{
    qDebug() << "Game login succeeded, server:" << loginResult.serverInfo.serverId;

    // === 显示成功消息 ===
    addChatMessage("System", QString("Connected to server: %1 (%2)")
                   .arg(loginResult.serverInfo.serverId)
                   .arg(loginResult.serverInfo.region), Qt::blue);
}

/**
 * @brief 游戏登录失败处理
 * @param error 错误信息
 */
void SnakeGameWidget::onGameLoginFailed(const QString &error)
{
    qWarning() << "Game login failed:" << error;

    // === 显示错误消息 ===
    showErrorMessage("Connection Failed", QString("Failed to connect to game server:\n%1").arg(error));

    // === 重置连接按钮 ===
    m_connectButton->setEnabled(true);
    m_connectButton->setText("Connect");
}

/**
 * @brief 房间列表获取处理
 * @param rooms 房间列表
 * @param totalCount 总房间数
 */
void SnakeGameWidget::onRoomListReceived(const QList<SnakeApiClient::RoomInfo> &rooms)
{
    qDebug() << "Received" << rooms.size() << "rooms";

    m_availableRooms = rooms;
    updateRoomList();
}

/**
 * @brief 房间创建成功处理
 * @param roomInfo 房间信息
 */
void SnakeGameWidget::onRoomCreated(const SnakeApiClient::RoomInfo &roomInfo)
{
    qDebug() << "Room created successfully:" << roomInfo.roomId;

    // === 重置创建房间按钮 ===
    m_createRoomButton->setEnabled(true);
    m_createRoomButton->setText("Create Room");

    // === 显示成功消息 ===
    addChatMessage("System", QString("Room '%1' created successfully").arg(roomInfo.roomName), Qt::green);

    // === 自动加入创建的房间 ===
    joinGameRoom(roomInfo.roomId);
}

/**
 * @brief 加入房间成功处理
 * @param roomId 房间ID
 */
void SnakeGameWidget::onRoomJoined(const QString &roomId)
{
    qDebug() << "Joined room successfully:" << roomId;

    m_currentRoomId = roomId;

    // === 重置加入房间按钮 ===
    m_joinRoomButton->setEnabled(true);
    m_joinRoomButton->setText("Join Room");

    // === 切换到游戏页面 ===
    switchToPage(GamePage_Playing);

    // === 显示成功消息 ===
    addChatMessage("System", QString("Joined room: %1").arg(roomId), Qt::green);

    // === 更新游戏信息 ===
    updateGameInfo();
}

/**
 * @brief 离开房间处理
 */
void SnakeGameWidget::onRoomLeft()
{
    qDebug() << "Left room";

    m_currentRoomId.clear();

    // === 显示消息 ===
    addChatMessage("System", "Left the room", Qt::blue);

    // === 切换到大厅页面 ===
    switchToPage(LobbyPage);
}

/**
 * @brief 游戏开始处理
 */
void SnakeGameWidget::onGameStarted()
{
    qDebug() << "Game started";

    // === 显示游戏开始消息 ===
    addChatMessage("System", "Game started! Use WASD or arrow keys to control your snake.", Qt::green);

    // === 确保在游戏页面 ===
    if (m_currentPage != GamePage_Playing) {
        switchToPage(GamePage_Playing);
    }

    // === 设置焦点以接收键盘输入 ===
    setFocus();
}

/**
 * @brief 游戏结束处理
 * @param results 游戏结果
 */
void SnakeGameWidget::onGameEnded(const QJsonObject &results)
{
    qDebug() << "Game ended";

    // === 显示游戏结果 ===
    QString resultText = "Game ended!";
    if (results.contains("winner")) {
        QString winner = results["winner"].toString();
        resultText += QString(" Winner: %1").arg(winner);
    }

    if (results.contains("final_scores")) {
        QJsonArray scores = results["final_scores"].toArray();
        resultText += "\nFinal Scores:";
        for (const QJsonValue &scoreValue : scores) {
            QJsonObject scoreObj = scoreValue.toObject();
            QString playerId = scoreObj["player_id"].toString();
            int score = scoreObj["score"].toInt();
            resultText += QString("\n%1: %2").arg(playerId).arg(score);
        }
    }

    addChatMessage("System", resultText, Qt::magenta);

    // === 显示结果对话框 ===
    QMessageBox::information(this, "Game Ended", resultText);
}

/**
 * @brief 玩家加入处理
 * @param playerId 玩家ID
 * @param playerName 玩家名称
 */
void SnakeGameWidget::onPlayerJoined(const QString &playerId, const QString &playerName)
{
    qDebug() << "Player joined:" << playerName << "(" << playerId << ")";

    addChatMessage("System", QString("%1 joined the game").arg(playerName), Qt::blue);
    updateGameInfo();
}

/**
 * @brief 玩家离开处理
 * @param playerId 玩家ID
 */
void SnakeGameWidget::onPlayerLeft(const QString &playerId)
{
    qDebug() << "Player left:" << playerId;

    addChatMessage("System", QString("Player %1 left the game").arg(playerId), Qt::gray);
    updateGameInfo();
}

/**
 * @brief 聊天消息接收处理
 * @param senderId 发送者ID
 * @param senderName 发送者名称
 * @param message 消息内容
 */
void SnakeGameWidget::onChatMessageReceived(const QString &senderId, const QString &senderName, const QString &message)
{
    Q_UNUSED(senderId)

    // === 添加聊天消息 ===
    addChatMessage(senderName, message);
}

/**
 * @brief 玩家统计信息获取处理
 * @param stats 玩家统计信息
 */
void SnakeGameWidget::onPlayerStatsReceived(const SnakeApiClient::PlayerStats &stats)
{
    qDebug() << "Received player stats for:" << stats.username;

    // === 更新统计页面 ===
    QString statsText = QString(
        "Player: %1\n"
        "Level: %2\n"
        "Total Score: %3\n"
        "Games Played: %4\n"
        "Games Won: %5\n"
        "Win Rate: %6%\n"
        "Longest Snake: %7\n"
        "Total Play Time: %8 minutes\n"
        "Last Played: %9"
    ).arg(stats.username)
     .arg(stats.level)
     .arg(stats.totalScore)
     .arg(stats.gamesPlayed)
     .arg(stats.gamesWon)
     .arg(stats.winRate * 100, 0, 'f', 1)
     .arg(stats.longestSnake)
     .arg(stats.totalPlayTime / 60)
     .arg(QDateTime::fromMSecsSinceEpoch(stats.lastPlayed).toString());

    m_playerStatsLabel->setText(statsText);
}

/**
 * @brief 排行榜获取处理
 * @param leaderboard 排行榜数据
 * @param type 排行榜类型
 */
void SnakeGameWidget::onLeaderboardReceived(const QJsonArray &leaderboard, const QString &type)
{
    qDebug() << "Received leaderboard with" << leaderboard.size() << "entries, type:" << type;

    // === 更新排行榜显示 ===
    QString leaderboardText = QString("=== %1 Leaderboard ===\n\n").arg(type.toUpper());

    for (int i = 0; i < leaderboard.size(); ++i) {
        QJsonObject entry = leaderboard[i].toObject();
        QString username = entry["username"].toString();
        int score = entry["score"].toInt();
        int rank = i + 1;

        leaderboardText += QString("%1. %2 - %3\n").arg(rank).arg(username).arg(score);
    }

    m_leaderboardEdit->setPlainText(leaderboardText);
}

/**
 * @brief 连接按钮点击处理
 */
void SnakeGameWidget::onConnectButtonClicked()
{
    QString region = m_regionComboBox->currentText();
    if (region == "Auto") {
        region.clear(); // 自动选择地区
    }

    connectToGameServer(region);
}

/**
 * @brief 断开连接按钮点击处理
 */
void SnakeGameWidget::onDisconnectButtonClicked()
{
    disconnectFromGameServer();
}

/**
 * @brief 创建房间按钮点击处理
 */
void SnakeGameWidget::onCreateRoomButtonClicked()
{
    createGameRoom();
}

/**
 * @brief 加入房间按钮点击处理
 */
void SnakeGameWidget::onJoinRoomButtonClicked()
{
    QListWidgetItem *currentItem = m_roomListWidget->currentItem();
    if (!currentItem) {
        showErrorMessage("Error", "Please select a room to join");
        return;
    }

    QString roomId = currentItem->data(Qt::UserRole).toString();
    joinGameRoom(roomId);
}

/**
 * @brief 离开房间按钮点击处理
 */
void SnakeGameWidget::onLeaveRoomButtonClicked()
{
    leaveGameRoom();
}

/**
 * @brief 刷新房间按钮点击处理
 */
void SnakeGameWidget::onRefreshRoomsButtonClicked()
{
    if (isConnectedToGame()) {
        m_gameManager->getRoomList();
    }
}

/**
 * @brief 发送聊天按钮点击处理
 */
void SnakeGameWidget::onSendChatButtonClicked()
{
    QString message = m_chatInputEdit->text().trimmed();
    if (message.isEmpty()) {
        return;
    }

    if (!isInGame()) {
        showErrorMessage("Error", "Not in a game room");
        return;
    }

    // === 发送聊天消息 ===
    m_gameManager->sendChatMessage(message);

    // === 清空输入框 ===
    m_chatInputEdit->clear();
}

/**
 * @brief 设置按钮点击处理
 */
void SnakeGameWidget::onSettingsButtonClicked()
{
    switchToPage(SettingsPage);
}

/**
 * @brief 统计按钮点击处理
 */
void SnakeGameWidget::onStatsButtonClicked()
{
    switchToPage(StatsPage);

    // === 获取玩家统计信息 ===
    if (isConnectedToGame()) {
        m_gameManager->getPlayerStats();
        m_gameManager->getLeaderboard("all_time");
    }
}

// 删除：重复的onBackToLobbyButtonClicked方法，使用后面更完整的版本

/**
 * @brief 房间选择改变处理
 */
void SnakeGameWidget::onRoomSelectionChanged()
{
    QListWidgetItem *currentItem = m_roomListWidget->currentItem();
    m_joinRoomButton->setEnabled(currentItem != nullptr && isConnectedToGame());
}

/**
 * @brief 聊天输入框回车处理
 */
void SnakeGameWidget::onChatInputReturnPressed()
{
    onSendChatButtonClicked();
}

/**
 * @brief 状态更新定时器处理
 */
void SnakeGameWidget::onStatusUpdateTimer()
{
    updateConnectionStatus();

    if (m_currentPage == GamePage_Playing) {
        updateGameInfo();
    }
}

/**
 * @brief 房间列表刷新定时器处理
 */
void SnakeGameWidget::onRoomListRefreshTimer()
{
    if (m_currentPage == LobbyPage && isConnectedToGame()) {
        m_gameManager->getRoomList();
    }
}

/**
 * @brief 设置UI界面
 */
void SnakeGameWidget::setupUI()
{
    // === 创建主布局（左右布局）===
    m_mainLayout = new QHBoxLayout(this);
    m_mainLayout->setContentsMargins(10, 10, 10, 10);
    m_mainLayout->setSpacing(15);

    // === 创建左侧面板 ===
    m_leftPanel = new QWidget();
    m_leftPanel->setObjectName("leftPanel");
    m_leftPanel->setMinimumWidth(300);
    m_leftPanel->setMaximumWidth(400);

    // === 创建右侧面板 ===
    m_rightPanel = new QWidget();
    m_rightPanel->setObjectName("rightPanel");

    // === 设置左右面板布局 ===
    setupLeftPanel();
    setupRightPanel();

    // === 添加到主布局 ===
    m_mainLayout->addWidget(m_leftPanel, 1);    // 左侧占1份
    m_mainLayout->addWidget(m_rightPanel, 2);   // 右侧占2份

    // === 设置各个页面（保持兼容性）===
    setupLobbyPage();
    setupGamePage();
    setupSinglePlayerPage();
    setupSettingsPage();
    setupStatsPage();
}

/**
 * @brief 设置左侧面板
 *
 * 左侧面板分为左右两部分：
 * - 左部分：游戏控制、房间信息等
 * - 右部分：聊天、玩家列表等
 */
void SnakeGameWidget::setupLeftPanel()
{
    // === 创建左侧面板的垂直布局（单人模式优化） ===
    m_leftPanelLayout = new QVBoxLayout(m_leftPanel);
    m_leftPanelLayout->setContentsMargins(10, 10, 10, 10);
    m_leftPanelLayout->setSpacing(15);

    // === 创建房间列表区域 ===
    setupRoomListPanel();

    // === 创建房间操作区域 ===
    setupRoomOperationsPanel();

    // === 添加返回大厅按钮 ===
    setupBackToLobbyButton();

    // === 添加WebSocket连接状态验证 ===
    setupWebSocketConnectionVerification();
}

/**
 * @brief 设置房间列表面板
 *
 * 显示可用的游戏房间列表
 */
void SnakeGameWidget::setupRoomListPanel()
{
    QGroupBox *roomListGroup = new QGroupBox("🏠 游戏房间");
    roomListGroup->setObjectName("roomListGroup");
    roomListGroup->setMinimumHeight(300);

    QVBoxLayout *roomListLayout = new QVBoxLayout(roomListGroup);
    roomListLayout->setContentsMargins(10, 15, 10, 10);
    roomListLayout->setSpacing(10);

    // === 房间列表 ===
    m_roomListWidget = new QListWidget();
    m_roomListWidget->setObjectName("roomListWidget");
    m_roomListWidget->setMinimumHeight(200);

    // === 刷新按钮 ===
    m_refreshRoomsButton = new QPushButton("🔄 刷新房间列表");
    m_refreshRoomsButton->setObjectName("refreshRoomsButton");
    m_refreshRoomsButton->setMinimumHeight(35);

    roomListLayout->addWidget(m_roomListWidget, 1);
    roomListLayout->addWidget(m_refreshRoomsButton);

    m_leftPanelLayout->addWidget(roomListGroup, 2);
}

/**
 * @brief 设置房间操作面板
 *
 * 包含创建房间、加入房间等操作
 */
void SnakeGameWidget::setupRoomOperationsPanel()
{
    QGroupBox *roomOpsGroup = new QGroupBox("🎮 房间操作");
    roomOpsGroup->setObjectName("roomOpsGroup");
    roomOpsGroup->setMinimumHeight(200);

    QVBoxLayout *roomOpsLayout = new QVBoxLayout(roomOpsGroup);
    roomOpsLayout->setContentsMargins(10, 15, 10, 10);
    roomOpsLayout->setSpacing(10);

    // === 创建房间按钮 ===
    m_createRoomButton = new QPushButton("➕ 创建房间");
    m_createRoomButton->setObjectName("createRoomButton");
    m_createRoomButton->setMinimumHeight(40);

    // === 加入房间按钮 ===
    m_joinRoomButton = new QPushButton("🚪 加入房间");
    m_joinRoomButton->setObjectName("joinRoomButton");
    m_joinRoomButton->setMinimumHeight(40);
    m_joinRoomButton->setEnabled(false);

    // === 离开房间按钮 ===
    m_leaveRoomButton = new QPushButton("🚶 离开房间");
    m_leaveRoomButton->setObjectName("leaveRoomButton");
    m_leaveRoomButton->setMinimumHeight(40);
    m_leaveRoomButton->setEnabled(false);

    roomOpsLayout->addWidget(m_createRoomButton);
    roomOpsLayout->addWidget(m_joinRoomButton);
    roomOpsLayout->addWidget(m_leaveRoomButton);
    roomOpsLayout->addStretch();

    m_leftPanelLayout->addWidget(roomOpsGroup, 1);
}

/**
 * @brief 设置返回大厅按钮
 *
 * 添加返回游戏入口界面的按钮
 */
void SnakeGameWidget::setupBackToLobbyButton()
{
    m_backToLobbyButton = new QPushButton("🏠 返回大厅");
    m_backToLobbyButton->setObjectName("backToLobbyButton");
    m_backToLobbyButton->setMinimumHeight(45);
    m_backToLobbyButton->setStyleSheet(
        "QPushButton#backToLobbyButton {"
        "   background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
        "       stop:0 rgba(231, 76, 60, 0.8), stop:1 rgba(231, 76, 60, 0.6));"
        "   border: 2px solid rgba(231, 76, 60, 0.5);"
        "   border-radius: 8px;"
        "   color: white;"
        "   font-size: 16px;"
        "   font-weight: bold;"
        "   text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);"
        "}"
        "QPushButton#backToLobbyButton:hover {"
        "   background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
        "       stop:0 rgba(231, 76, 60, 0.9), stop:1 rgba(231, 76, 60, 0.7));"
        "   border: 2px solid rgba(231, 76, 60, 0.7);"
        "   transform: translateY(-2px);"
        "}"
        "QPushButton#backToLobbyButton:pressed {"
        "   background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
        "       stop:0 rgba(231, 76, 60, 0.7), stop:1 rgba(231, 76, 60, 0.5));"
        "   transform: translateY(0px);"
        "}"
    );

    m_leftPanelLayout->addWidget(m_backToLobbyButton);
}

/**
 * @brief 设置WebSocket连接状态验证
 *
 * 添加连接状态指示器，证明WebSocket连接成功
 */
void SnakeGameWidget::setupWebSocketConnectionVerification()
{
    // === 创建连接状态指示器 ===
    QWidget *connectionIndicator = new QWidget();
    connectionIndicator->setObjectName("connectionIndicator");
    connectionIndicator->setFixedHeight(60);

    QHBoxLayout *indicatorLayout = new QHBoxLayout(connectionIndicator);
    indicatorLayout->setContentsMargins(10, 10, 10, 10);
    indicatorLayout->setSpacing(10);

    // === 连接状态图标 ===
    m_connectionStatusIcon = new QLabel("🔴");
    m_connectionStatusIcon->setObjectName("connectionStatusIcon");
    m_connectionStatusIcon->setFixedSize(30, 30);
    m_connectionStatusIcon->setAlignment(Qt::AlignCenter);
    m_connectionStatusIcon->setStyleSheet(
        "QLabel {"
        "   font-size: 20px;"
        "   background: rgba(231, 76, 60, 0.2);"
        "   border: 2px solid rgba(231, 76, 60, 0.5);"
        "   border-radius: 15px;"
        "}"
    );

    // === 连接状态文本 ===
    m_connectionStatusText = new QLabel("WebSocket: 未连接");
    m_connectionStatusText->setObjectName("connectionStatusText");
    m_connectionStatusText->setStyleSheet(
        "QLabel {"
        "   color: #E74C3C;"
        "   font-size: 14px;"
        "   font-weight: bold;"
        "}"
    );

    // === 连接详情按钮 ===
    m_connectionDetailsButton = new QPushButton("📊 连接详情");
    m_connectionDetailsButton->setObjectName("connectionDetailsButton");
    m_connectionDetailsButton->setFixedSize(100, 30);
    m_connectionDetailsButton->setStyleSheet(
        "QPushButton {"
        "   background: rgba(52, 152, 219, 0.8);"
        "   border: 1px solid rgba(52, 152, 219, 0.6);"
        "   border-radius: 6px;"
        "   color: white;"
        "   font-size: 12px;"
        "   font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "   background: rgba(52, 152, 219, 0.9);"
        "}"
    );

    indicatorLayout->addWidget(m_connectionStatusIcon);
    indicatorLayout->addWidget(m_connectionStatusText, 1);
    indicatorLayout->addWidget(m_connectionDetailsButton);

    // === 设置样式 ===
    connectionIndicator->setStyleSheet(
        "QWidget#connectionIndicator {"
        "   background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
        "       stop:0 rgba(255, 255, 255, 0.1), stop:1 rgba(255, 255, 255, 0.05));"
        "   border: 1px solid rgba(255, 255, 255, 0.2);"
        "   border-radius: 10px;"
        "   margin: 5px;"
        "}"
    );

    m_leftPanelLayout->addWidget(connectionIndicator);
}

/**
 * @brief 设置右侧面板
 *
 * 右侧面板分为上中下三部分：
 * - 上部分：游戏状态、连接信息等
 * - 中部分：游戏画面、主要内容区域
 * - 下部分：控制按钮、操作面板等
 */
void SnakeGameWidget::setupRightPanel()
{
    // === 创建右侧面板的上中下布局 ===
    m_rightPanelLayout = new QVBoxLayout(m_rightPanel);
    m_rightPanelLayout->setContentsMargins(5, 5, 5, 5);
    m_rightPanelLayout->setSpacing(10);

    // === 创建右侧面板的上中下三部分 ===
    m_rightTopPanel = new QWidget();
    m_rightTopPanel->setObjectName("rightTopPanel");
    m_rightTopPanel->setFixedHeight(80);

    m_rightMiddlePanel = new QWidget();
    m_rightMiddlePanel->setObjectName("rightMiddlePanel");
    m_rightMiddlePanel->setMinimumHeight(400);

    m_rightBottomPanel = new QWidget();
    m_rightBottomPanel->setObjectName("rightBottomPanel");
    m_rightBottomPanel->setFixedHeight(60);

    // === 设置各部分内容 ===
    setupRightTopPanel();
    setupRightMiddlePanel();
    setupRightBottomPanel();

    // === 添加到右侧面板布局 ===
    m_rightPanelLayout->addWidget(m_rightTopPanel);
    m_rightPanelLayout->addWidget(m_rightMiddlePanel, 1);  // 中部分占主要空间
    m_rightPanelLayout->addWidget(m_rightBottomPanel);
}

// 删除：未使用的setupLeftLeftPanel方法

// 删除：未使用的setupLeftRightPanel方法

/**
 * @brief 设置右侧面板的上部分
 *
 * 包含游戏状态、连接信息等
 */
void SnakeGameWidget::setupRightTopPanel()
{
    QHBoxLayout *layout = new QHBoxLayout(m_rightTopPanel);
    layout->setContentsMargins(10, 5, 10, 5);
    layout->setSpacing(15);

    // === 游戏信息区域 ===
    QGroupBox *gameInfoGroup = new QGroupBox("游戏信息");
    gameInfoGroup->setObjectName("gameInfoGroup");
    QHBoxLayout *gameInfoLayout = new QHBoxLayout(gameInfoGroup);

    m_roomIdLabel = new QLabel("房间: 未连接");
    m_roomIdLabel->setObjectName("roomIdLabel");

    m_playerCountLabel = new QLabel("玩家: 0/0");
    m_playerCountLabel->setObjectName("playerCountLabel");

    m_gameStatusLabel = new QLabel("状态: 等待中");
    m_gameStatusLabel->setObjectName("gameStatusLabel");

    gameInfoLayout->addWidget(m_roomIdLabel);
    gameInfoLayout->addWidget(m_playerCountLabel);
    gameInfoLayout->addWidget(m_gameStatusLabel);
    gameInfoLayout->addStretch();

    // === 玩家统计区域 ===
    QGroupBox *playerStatsGroup = new QGroupBox("玩家统计");
    playerStatsGroup->setObjectName("playerStatsGroup");
    QHBoxLayout *playerStatsLayout = new QHBoxLayout(playerStatsGroup);

    m_scoreLabel = new QLabel("分数: 0");
    m_scoreLabel->setObjectName("scoreLabel");

    m_lengthLabel = new QLabel("长度: 1");
    m_lengthLabel->setObjectName("lengthLabel");

    playerStatsLayout->addWidget(m_scoreLabel);
    playerStatsLayout->addWidget(m_lengthLabel);
    playerStatsLayout->addStretch();

    // === 添加到布局 ===
    layout->addWidget(gameInfoGroup, 2);
    layout->addWidget(playerStatsGroup, 1);
}

/**
 * @brief 设置右侧面板的中部分
 *
 * 主要的游戏画面区域
 */
void SnakeGameWidget::setupRightMiddlePanel()
{
    QVBoxLayout *layout = new QVBoxLayout(m_rightMiddlePanel);
    layout->setContentsMargins(5, 5, 5, 5);
    layout->setSpacing(5);

    // === 创建堆叠窗口用于页面切换 ===
    m_stackedWidget = new QStackedWidget();
    m_stackedWidget->setObjectName("gameStackedWidget");

    // === 添加各个页面到堆叠窗口 ===
    // 大厅页面 (索引0)
    QLabel *lobbyLabel = new QLabel("游戏大厅 - 选择房间开始游戏");
    lobbyLabel->setAlignment(Qt::AlignCenter);
    lobbyLabel->setStyleSheet(
        "QLabel {"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 rgba(255, 255, 255, 0.12), stop:1 rgba(255, 255, 255, 0.08));"
        "   border: 2px solid rgba(76, 175, 80, 0.3);"
        "   border-radius: 20px;"
        "   color: #ffffff;"
        "   font-size: 20px;"
        "   font-weight: bold;"
        "   text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);"
        "}"
    );
    m_stackedWidget->addWidget(lobbyLabel);  // 索引0: LobbyPage

    // 多人游戏页面 (索引1)
    m_stackedWidget->addWidget(m_gameRenderer);  // 索引1: GamePage_Playing

    // 单人游戏页面 (索引2) - 稍后在setupSinglePlayerPage中添加
    QLabel *singlePlayerPlaceholder = new QLabel("单人游戏页面");
    singlePlayerPlaceholder->setAlignment(Qt::AlignCenter);
    singlePlayerPlaceholder->setStyleSheet(
        "QLabel {"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 rgba(76, 175, 80, 0.15), stop:1 rgba(76, 175, 80, 0.1));"
        "   border: 2px solid rgba(76, 175, 80, 0.4);"
        "   border-radius: 20px;"
        "   color: #ffffff;"
        "   font-size: 20px;"
        "   font-weight: bold;"
        "   text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);"
        "}"
    );
    m_stackedWidget->addWidget(singlePlayerPlaceholder);  // 索引2: SinglePlayerPage (占位符)

    // 设置页面 (索引3)
    QLabel *settingsLabel = new QLabel("设置页面");
    settingsLabel->setAlignment(Qt::AlignCenter);
    settingsLabel->setStyleSheet(
        "QLabel {"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 rgba(149, 165, 166, 0.15), stop:1 rgba(149, 165, 166, 0.1));"
        "   border: 2px solid rgba(149, 165, 166, 0.4);"
        "   border-radius: 20px;"
        "   color: #ffffff;"
        "   font-size: 20px;"
        "   font-weight: bold;"
        "   text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);"
        "}"
    );
    m_stackedWidget->addWidget(settingsLabel);  // 索引3: SettingsPage

    // 统计页面 (索引4)
    QLabel *statsLabel = new QLabel("统计页面");
    statsLabel->setAlignment(Qt::AlignCenter);
    statsLabel->setStyleSheet(
        "QLabel {"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 rgba(155, 89, 182, 0.15), stop:1 rgba(155, 89, 182, 0.1));"
        "   border: 2px solid rgba(155, 89, 182, 0.4);"
        "   border-radius: 20px;"
        "   color: #ffffff;"
        "   font-size: 20px;"
        "   font-weight: bold;"
        "   text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);"
        "}"
    );
    m_stackedWidget->addWidget(statsLabel);  // 索引4: StatsPage

    layout->addWidget(m_stackedWidget);

    // === 默认显示大厅页面 ===
    m_stackedWidget->setCurrentIndex(0);
    m_currentPage = LobbyPage;
}

/**
 * @brief 设置右侧面板的下部分
 *
 * 包含控制按钮、操作面板等
 */
void SnakeGameWidget::setupRightBottomPanel()
{
    QHBoxLayout *layout = new QHBoxLayout(m_rightBottomPanel);
    layout->setContentsMargins(10, 5, 10, 5);
    layout->setSpacing(10);

    // === 游戏控制按钮 ===
    m_leaveRoomButton = new QPushButton("离开房间");
    m_leaveRoomButton->setObjectName("leaveRoomButton");
    m_leaveRoomButton->setEnabled(false);

    m_backToLobbyButton = new QPushButton("返回大厅");
    m_backToLobbyButton->setObjectName("backToLobbyButton");

    // === 地区选择 ===
    QLabel *regionLabel = new QLabel("地区:");
    regionLabel->setObjectName("regionLabel");

    m_regionComboBox = new QComboBox();
    m_regionComboBox->setObjectName("regionComboBox");
    m_regionComboBox->addItems({"自动", "美国东部", "美国西部", "欧洲", "亚洲"});
    m_regionComboBox->setMaximumWidth(120);

    // === 添加到布局 ===
    layout->addWidget(m_leaveRoomButton);
    layout->addWidget(m_backToLobbyButton);
    layout->addStretch();  // 添加弹簧
    layout->addWidget(regionLabel);
    layout->addWidget(m_regionComboBox);
}

/**
 * @brief 设置大厅页面
 */
void SnakeGameWidget::setupLobbyPage()
{
    m_lobbyWidget = new QWidget();
    m_lobbyLayout = new QVBoxLayout(m_lobbyWidget);
    m_lobbyLayout->setContentsMargins(Config::getStandardMargin(), Config::getStandardMargin(),
                                     Config::getStandardMargin(), Config::getStandardMargin());
    m_lobbyLayout->setSpacing(Config::getStandardSpacing());

    // === 连接控制区域 ===
    m_connectionLayout = new QHBoxLayout();

    m_connectionStatusLabel = new QLabel("Disconnected");
    m_connectionStatusLabel->setStyleSheet("QLabel { color: #E74C3C; font-weight: bold; }");

    m_regionComboBox = new QComboBox();
    m_regionComboBox->addItems({"Auto", "US-East", "US-West", "Europe", "Asia"});
    m_regionComboBox->setCurrentText("Auto");

    m_connectButton = new QPushButton("🌐 Connect");
    m_connectButton->setMinimumWidth(100);
    m_connectButton->setProperty("class", "primary");  // 设置为主要按钮样式

    m_disconnectButton = new QPushButton("🔌 Disconnect");
    m_disconnectButton->setMinimumWidth(100);
    m_disconnectButton->setEnabled(false);

    m_connectionLayout->addWidget(new QLabel("Status:"));
    m_connectionLayout->addWidget(m_connectionStatusLabel);
    m_connectionLayout->addStretch();
    m_connectionLayout->addWidget(new QLabel("Region:"));
    m_connectionLayout->addWidget(m_regionComboBox);
    m_connectionLayout->addWidget(m_connectButton);
    m_connectionLayout->addWidget(m_disconnectButton);

    m_lobbyLayout->addLayout(m_connectionLayout);

    // === 房间管理区域 ===
    m_roomGroupBox = new QGroupBox("Game Rooms");
    m_roomLayout = new QVBoxLayout(m_roomGroupBox);

    m_roomControlLayout = new QHBoxLayout();
    m_createRoomButton = new QPushButton("➕ Create Room");
    m_createRoomButton->setEnabled(false);
    m_createRoomButton->setProperty("class", "primary");  // 主要操作按钮
    m_joinRoomButton = new QPushButton("🏠 Join Room");
    m_joinRoomButton->setEnabled(false);
    m_joinRoomButton->setProperty("class", "primary");    // 主要操作按钮
    m_refreshRoomsButton = new QPushButton("🔄 Refresh");
    m_refreshRoomsButton->setEnabled(false);

    m_roomControlLayout->addWidget(m_createRoomButton);
    m_roomControlLayout->addWidget(m_joinRoomButton);
    m_roomControlLayout->addStretch();
    m_roomControlLayout->addWidget(m_refreshRoomsButton);

    m_roomListWidget = new QListWidget();
    m_roomListWidget->setAlternatingRowColors(true);

    m_roomLayout->addLayout(m_roomControlLayout);
    m_roomLayout->addWidget(m_roomListWidget);

    m_lobbyLayout->addWidget(m_roomGroupBox);

    // === 底部按钮 ===
    QHBoxLayout *bottomLayout = new QHBoxLayout();
    QPushButton *settingsButton = new QPushButton("Settings");
    QPushButton *statsButton = new QPushButton("Statistics");

    bottomLayout->addWidget(settingsButton);
    bottomLayout->addWidget(statsButton);
    bottomLayout->addStretch();

    m_lobbyLayout->addLayout(bottomLayout);

    // === 连接信号槽 ===
    connect(m_connectButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onConnectButtonClicked);
    connect(m_disconnectButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onDisconnectButtonClicked);
    connect(m_createRoomButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onCreateRoomButtonClicked);
    connect(m_joinRoomButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onJoinRoomButtonClicked);
    connect(m_refreshRoomsButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onRefreshRoomsButtonClicked);
    connect(m_roomListWidget, &QListWidget::itemSelectionChanged,
            this, &SnakeGameWidget::onRoomSelectionChanged);
    connect(settingsButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onSettingsButtonClicked);
    connect(statsButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onStatsButtonClicked);
}

/**
 * @brief 设置游戏页面
 */
void SnakeGameWidget::setupGamePage()
{
    m_gameWidget = new QWidget();
    m_gameLayout = new QHBoxLayout(m_gameWidget);
    m_gameLayout->setContentsMargins(0, 0, 0, 0);
    m_gameLayout->setSpacing(0);

    // === 创建分割器 ===
    m_gameSplitter = new QSplitter(Qt::Horizontal);
    m_gameLayout->addWidget(m_gameSplitter);

    // === 游戏渲染区域 ===
    m_gameSplitter->addWidget(m_gameRenderer);

    // === 游戏控制面板 ===
    m_gameControlWidget = new QWidget();
    m_gameControlWidget->setMinimumWidth(300);
    m_gameControlWidget->setMaximumWidth(400);
    m_gameControlLayout = new QVBoxLayout(m_gameControlWidget);
    m_gameControlLayout->setContentsMargins(Config::getStandardMargin(), Config::getStandardMargin(),
                                           Config::getStandardMargin(), Config::getStandardMargin());
    m_gameControlLayout->setSpacing(Config::getStandardSpacing());

    // === 游戏信息区域 ===
    m_gameInfoGroupBox = new QGroupBox("Game Info");
    m_gameInfoLayout = new QVBoxLayout(m_gameInfoGroupBox);

    m_roomIdLabel = new QLabel("Room: -");
    m_playerCountLabel = new QLabel("Players: 0/4");
    m_gameStatusLabel = new QLabel("Status: Waiting");
    m_scoreLabel = new QLabel("Score: 0");
    m_lengthLabel = new QLabel("Length: 1");

    m_gameInfoLayout->addWidget(m_roomIdLabel);
    m_gameInfoLayout->addWidget(m_playerCountLabel);
    m_gameInfoLayout->addWidget(m_gameStatusLabel);
    m_gameInfoLayout->addWidget(m_scoreLabel);
    m_gameInfoLayout->addWidget(m_lengthLabel);

    m_gameControlLayout->addWidget(m_gameInfoGroupBox);

    // === 聊天区域 ===
    m_chatGroupBox = new QGroupBox("Chat");
    m_chatLayout = new QVBoxLayout(m_chatGroupBox);

    m_chatDisplayEdit = new QTextEdit();
    m_chatDisplayEdit->setReadOnly(true);
    m_chatDisplayEdit->setMaximumHeight(200);

    m_chatInputLayout = new QHBoxLayout();
    m_chatInputEdit = new QLineEdit();
    m_chatInputEdit->setPlaceholderText("Type your message...");
    m_sendChatButton = new QPushButton("Send");

    m_chatInputLayout->addWidget(m_chatInputEdit);
    m_chatInputLayout->addWidget(m_sendChatButton);

    m_chatLayout->addWidget(m_chatDisplayEdit);
    m_chatLayout->addLayout(m_chatInputLayout);

    m_gameControlLayout->addWidget(m_chatGroupBox);

    // === 控制按钮 ===
    m_leaveRoomButton = new QPushButton("Leave Room");
    m_backToLobbyButton = new QPushButton("Back to Lobby");

    m_gameControlLayout->addWidget(m_leaveRoomButton);
    m_gameControlLayout->addWidget(m_backToLobbyButton);
    m_gameControlLayout->addStretch();

    // === 添加控制面板到分割器 ===
    m_gameSplitter->addWidget(m_gameControlWidget);

    // === 设置分割器比例 ===
    m_gameSplitter->setStretchFactor(0, 3); // 游戏区域占3/4
    m_gameSplitter->setStretchFactor(1, 1); // 控制面板占1/4

    // === 连接信号槽 ===
    connect(m_sendChatButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onSendChatButtonClicked);
    connect(m_chatInputEdit, &QLineEdit::returnPressed,
            this, &SnakeGameWidget::onChatInputReturnPressed);
    connect(m_leaveRoomButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onLeaveRoomButtonClicked);
    connect(m_backToLobbyButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onBackToLobbyButtonClicked);
}

/**
 * @brief 设置单人游戏页面
 */
void SnakeGameWidget::setupSinglePlayerPage()
{
    // === 创建单人游戏组件 ===
    if (!m_singlePlayerWidget) {
        m_singlePlayerWidget = new SinglePlayerGameWidget();

        // === 连接信号槽 ===
        connect(m_singlePlayerWidget, &SinglePlayerGameWidget::directionChanged,
                this, &SnakeGameWidget::onSinglePlayerDirectionChanged);
        connect(m_singlePlayerWidget, &SinglePlayerGameWidget::pauseRequested,
                this, &SnakeGameWidget::onSinglePlayerPauseRequested);
        connect(m_singlePlayerWidget, &SinglePlayerGameWidget::resumeRequested,
                this, &SnakeGameWidget::onSinglePlayerResumeRequested);
        connect(m_singlePlayerWidget, &SinglePlayerGameWidget::restartRequested,
                this, &SnakeGameWidget::onSinglePlayerRestartRequested);
        connect(m_singlePlayerWidget, &SinglePlayerGameWidget::exitGameRequested,
                this, &SnakeGameWidget::onSinglePlayerExitRequested);

        // === 连接游戏管理器信号到单人游戏组件 ===
        connect(m_gameManager, &SnakeGameManager::gameStateUpdated,
                this, &SnakeGameWidget::onGameStateUpdatedForSinglePlayer);

        // === 如果stackedWidget已经存在，替换占位符 ===
        if (m_stackedWidget && m_stackedWidget->count() > 2) {
            // 移除占位符
            QWidget* placeholder = m_stackedWidget->widget(2);
            m_stackedWidget->removeWidget(placeholder);
            placeholder->deleteLater();

            // 插入单人游戏组件到索引2
            m_stackedWidget->insertWidget(2, m_singlePlayerWidget);
        }
    }

    qDebug() << "SnakeGameWidget: 单人游戏页面设置完成";
}

/**
 * @brief 设置设置页面
 */
void SnakeGameWidget::setupSettingsPage()
{
    m_settingsWidget = new QWidget();
    m_settingsLayout = new QVBoxLayout(m_settingsWidget);
    m_settingsLayout->setContentsMargins(Config::getStandardMargin(), Config::getStandardMargin(),
                                        Config::getStandardMargin(), Config::getStandardMargin());
    m_settingsLayout->setSpacing(Config::getStandardSpacing());

    // === 渲染设置 ===
    m_renderSettingsGroupBox = new QGroupBox("Render Settings");
    QFormLayout *renderFormLayout = new QFormLayout(m_renderSettingsGroupBox);

    m_themeComboBox = new QComboBox();
    m_themeComboBox->addItems({"default", "dark", "classic", "forest", "ocean", "neon", "sunset"});

    m_renderModeComboBox = new QComboBox();
    m_renderModeComboBox->addItems({"Classic", "Modern", "Minimal", "Retro"});

    m_cellSizeSpinBox = new QSpinBox();
    m_cellSizeSpinBox->setRange(10, 50);
    m_cellSizeSpinBox->setValue(20);
    m_cellSizeSpinBox->setSuffix(" px");

    m_animationsCheckBox = new QCheckBox("Enable Animations");
    m_animationsCheckBox->setChecked(true);

    m_particlesCheckBox = new QCheckBox("Enable Particle Effects");
    m_particlesCheckBox->setChecked(true);

    m_gridCheckBox = new QCheckBox("Show Grid");
    m_gridCheckBox->setChecked(true);

    renderFormLayout->addRow("Theme:", m_themeComboBox);
    renderFormLayout->addRow("Render Mode:", m_renderModeComboBox);
    renderFormLayout->addRow("Cell Size:", m_cellSizeSpinBox);
    renderFormLayout->addRow(m_animationsCheckBox);
    renderFormLayout->addRow(m_particlesCheckBox);
    renderFormLayout->addRow(m_gridCheckBox);

    m_settingsLayout->addWidget(m_renderSettingsGroupBox);

    // === 应用和返回按钮 ===
    QHBoxLayout *settingsButtonLayout = new QHBoxLayout();
    QPushButton *applyButton = new QPushButton("Apply Settings");
    QPushButton *backButton = new QPushButton("Back to Lobby");

    settingsButtonLayout->addWidget(applyButton);
    settingsButtonLayout->addStretch();
    settingsButtonLayout->addWidget(backButton);

    m_settingsLayout->addLayout(settingsButtonLayout);
    m_settingsLayout->addStretch();

    // === 连接信号槽 ===
    connect(applyButton, &QPushButton::clicked, [this]() {
        applySettings();
        showInfoMessage("Settings", "Settings applied successfully!");
    });
    connect(backButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onBackToLobbyButtonClicked);
}

/**
 * @brief 设置统计页面
 */
void SnakeGameWidget::setupStatsPage()
{
    m_statsWidget = new QWidget();
    m_statsLayout = new QVBoxLayout(m_statsWidget);
    m_statsLayout->setContentsMargins(Config::getStandardMargin(), Config::getStandardMargin(),
                                     Config::getStandardMargin(), Config::getStandardMargin());
    m_statsLayout->setSpacing(Config::getStandardSpacing());

    // === 玩家统计 ===
    QGroupBox *playerStatsGroupBox = new QGroupBox("Player Statistics");
    QVBoxLayout *playerStatsLayout = new QVBoxLayout(playerStatsGroupBox);

    m_playerStatsLabel = new QLabel("Loading player statistics...");
    m_playerStatsLabel->setAlignment(Qt::AlignTop);
    m_playerStatsLabel->setWordWrap(true);

    playerStatsLayout->addWidget(m_playerStatsLabel);
    m_statsLayout->addWidget(playerStatsGroupBox);

    // === 排行榜 ===
    QGroupBox *leaderboardGroupBox = new QGroupBox("Leaderboard");
    QVBoxLayout *leaderboardLayout = new QVBoxLayout(leaderboardGroupBox);

    m_leaderboardEdit = new QTextEdit();
    m_leaderboardEdit->setReadOnly(true);
    m_leaderboardEdit->setPlainText("Loading leaderboard...");

    leaderboardLayout->addWidget(m_leaderboardEdit);
    m_statsLayout->addWidget(leaderboardGroupBox);

    // === 返回按钮 ===
    QHBoxLayout *statsButtonLayout = new QHBoxLayout();
    QPushButton *refreshButton = new QPushButton("Refresh");
    QPushButton *backButton = new QPushButton("Back to Lobby");

    statsButtonLayout->addWidget(refreshButton);
    statsButtonLayout->addStretch();
    statsButtonLayout->addWidget(backButton);

    m_statsLayout->addLayout(statsButtonLayout);

    // === 连接信号槽 ===
    connect(refreshButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onStatsButtonClicked);
    connect(backButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onBackToLobbyButtonClicked);
}

/**
 * @brief 建立信号槽连接
 */
void SnakeGameWidget::setupConnections()
{
    // === 游戏管理器信号连接 ===
    connect(m_gameManager, &SnakeGameManager::connectionStatusChanged,
            this, &SnakeGameWidget::onConnectionStatusChanged);
    connect(m_gameManager, &SnakeGameManager::gameServersReceived,
            this, &SnakeGameWidget::onGameServersReceived);
    connect(m_gameManager, &SnakeGameManager::gameLoginSucceeded,
            this, &SnakeGameWidget::onGameLoginSucceeded);
    connect(m_gameManager, &SnakeGameManager::gameLoginFailed,
            this, &SnakeGameWidget::onGameLoginFailed);
    connect(m_gameManager, &SnakeGameManager::roomListReceived,
            this, &SnakeGameWidget::onRoomListReceived);
    connect(m_gameManager, &SnakeGameManager::roomCreated,
            this, [this](const QString &roomId) {
                // 创建一个临时的RoomInfo对象
                SnakeApiClient::RoomInfo roomInfo;
                roomInfo.roomId = roomId;
                onRoomCreated(roomInfo);
            });
    connect(m_gameManager, &SnakeGameManager::roomJoined,
            this, &SnakeGameWidget::onRoomJoined);
    connect(m_gameManager, &SnakeGameManager::roomLeft,
            this, &SnakeGameWidget::onRoomLeft);
    connect(m_gameManager, &SnakeGameManager::gameStarted,
            this, &SnakeGameWidget::onGameStarted);
    connect(m_gameManager, &SnakeGameManager::gameEnded,
            this, &SnakeGameWidget::onGameEnded);
    connect(m_gameManager, &SnakeGameManager::playerJoined,
            this, &SnakeGameWidget::onPlayerJoined);
    connect(m_gameManager, &SnakeGameManager::playerLeft,
            this, &SnakeGameWidget::onPlayerLeft);
    connect(m_gameManager, &SnakeGameManager::chatMessageReceived,
            this, &SnakeGameWidget::onChatMessageReceived);
    connect(m_gameManager, &SnakeGameManager::playerStatsReceived,
            this, &SnakeGameWidget::onPlayerStatsReceived);
    connect(m_gameManager, &SnakeGameManager::leaderboardReceived,
            this, &SnakeGameWidget::onLeaderboardReceived);

    // === 新增的信号连接 ===
    connect(m_backToLobbyButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onBackToLobbyButtonClicked);
    connect(m_connectionDetailsButton, &QPushButton::clicked,
            this, &SnakeGameWidget::onConnectionDetailsButtonClicked);
}

/**
 * @brief 更新连接状态显示
 */
void SnakeGameWidget::updateConnectionStatus()
{
    SnakeGameManager::ConnectionStatus status = m_gameManager->getConnectionStatus();

    QString statusText;
    QString statusColor;
    QString statusIcon;

    switch (status) {
    case SnakeGameManager::Disconnected:
        statusText = "WebSocket: 未连接";
        statusColor = "#E74C3C";
        statusIcon = "🔴";
        break;
    case SnakeGameManager::Connecting:
        statusText = "WebSocket: 连接中...";
        statusColor = "#F39C12";
        statusIcon = "🟡";
        break;
    case SnakeGameManager::Connected:
        statusText = "WebSocket: 已连接";
        statusColor = "#27AE60";
        statusIcon = "🟢";
        break;
    case SnakeGameManager::InGame:
        statusText = "WebSocket: 游戏中";
        statusColor = "#27AE60";
        statusIcon = "🎮";
        break;
    case SnakeGameManager::Error:
        statusText = "WebSocket: 连接错误";
        statusColor = "#E74C3C";
        statusIcon = "❌";
        break;
    }

    // === 更新连接状态指示器 ===
    if (m_connectionStatusIcon && m_connectionStatusText) {
        m_connectionStatusIcon->setText(statusIcon);
        m_connectionStatusText->setText(statusText);
        m_connectionStatusText->setStyleSheet(QString("QLabel { color: %1; font-size: 14px; font-weight: bold; }").arg(statusColor));

        // 更新图标背景色
        QString iconBgColor;
        if (status == SnakeGameManager::Connected || status == SnakeGameManager::InGame) {
            iconBgColor = "rgba(39, 174, 96, 0.2)";
        } else if (status == SnakeGameManager::Connecting) {
            iconBgColor = "rgba(243, 156, 18, 0.2)";
        } else {
            iconBgColor = "rgba(231, 76, 60, 0.2)";
        }

        m_connectionStatusIcon->setStyleSheet(QString(
            "QLabel {"
            "   font-size: 20px;"
            "   background: %1;"
            "   border: 2px solid %2;"
            "   border-radius: 15px;"
            "}"
        ).arg(iconBgColor, statusColor));
    }

    // === 兼容旧的连接状态标签 ===
    if (m_connectionStatusLabel) {
        m_connectionStatusLabel->setText(statusText);
        m_connectionStatusLabel->setStyleSheet(QString("QLabel { color: %1; font-weight: bold; }").arg(statusColor));
    }
}

/**
 * @brief 更新房间列表显示
 */
void SnakeGameWidget::updateRoomList()
{
    m_roomListWidget->clear();

    for (const SnakeApiClient::RoomInfo &room : m_availableRooms) {
        QString itemText = QString("%1 (%2/%3) - %4")
                          .arg(room.roomName)
                          .arg(room.currentPlayers)
                          .arg(room.maxPlayers)
                          .arg(room.status);

        QListWidgetItem *item = new QListWidgetItem(itemText);
        item->setData(Qt::UserRole, room.roomId);

        // === 根据房间状态设置颜色 ===
        if (room.status == "waiting") {
            item->setForeground(QColor(Config::getSuccessColor()));
        } else if (room.status == "playing") {
            item->setForeground(QColor(Config::getWarningColor()));
        } else if (room.status == "full") {
            item->setForeground(QColor(Config::getErrorColor()));
        }

        m_roomListWidget->addItem(item);
    }

    // === 更新按钮状态 ===
    onRoomSelectionChanged();
}

/**
 * @brief 更新游戏信息显示
 */
void SnakeGameWidget::updateGameInfo()
{
    if (!m_gameManager->getGameState()) {
        return;
    }

    SnakeGameState *gameState = m_gameManager->getGameState();

    // === 更新房间信息 ===
    m_roomIdLabel->setText(QString("Room: %1").arg(m_currentRoomId));
    m_playerCountLabel->setText(QString("Players: %1").arg(gameState->getPlayerCount()));

    // === 更新游戏状态 ===
    QString statusText;
    switch (gameState->getGameStatus()) {
    case SnakeGameState::GameStatus::Waiting:
        statusText = "Waiting for players";
        break;
    case SnakeGameState::GameStatus::Starting:
        statusText = "Game starting...";
        break;
    case SnakeGameState::GameStatus::Playing:
        statusText = "Playing";
        break;
    case SnakeGameState::GameStatus::Paused:
        statusText = "Paused";
        break;
    case SnakeGameState::GameStatus::Finished:
        statusText = "Game finished";
        break;
    case SnakeGameState::GameStatus::Error:
        statusText = "Error";
        break;
    }
    m_gameStatusLabel->setText(QString("Status: %1").arg(statusText));

    // === 更新玩家信息 ===
    const SnakeData *playerSnake = gameState->getCurrentPlayerSnake();
    if (playerSnake) {
        m_scoreLabel->setText(QString("Score: %1").arg(playerSnake->score));
        m_lengthLabel->setText(QString("Length: %1").arg(playerSnake->length));
    } else {
        m_scoreLabel->setText("Score: -");
        m_lengthLabel->setText("Length: -");
    }
}

/**
 * @brief 更新玩家统计信息
 */
void SnakeGameWidget::updatePlayerStats()
{
    if (isConnectedToGame()) {
        m_gameManager->getPlayerStats();
        m_gameManager->getLeaderboard("all_time");
    } else {
        m_playerStatsLabel->setText("Not connected to game server");
        m_leaderboardEdit->setPlainText("Not connected to game server");
    }
}

/**
 * @brief 添加聊天消息
 * @param sender 发送者
 * @param message 消息内容
 * @param color 消息颜色
 */
void SnakeGameWidget::addChatMessage(const QString &sender, const QString &message, const QColor &color)
{
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString formattedMessage = QString("[%1] %2: %3").arg(timestamp).arg(sender).arg(message);

    // === 设置消息颜色 ===
    QString colorName = color.name();
    QString htmlMessage = QString("<span style='color: %1'>%2</span>").arg(colorName).arg(formattedMessage);

    m_chatDisplayEdit->append(htmlMessage);

    // === 自动滚动到底部 ===
    QTextCursor cursor = m_chatDisplayEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    m_chatDisplayEdit->setTextCursor(cursor);
}

/**
 * @brief 显示错误消息
 * @param title 标题
 * @param message 消息内容
 */
void SnakeGameWidget::showErrorMessage(const QString &title, const QString &message)
{
    QMessageBox::critical(this, title, message);
}

/**
 * @brief 显示信息消息
 * @param title 标题
 * @param message 消息内容
 */
void SnakeGameWidget::showInfoMessage(const QString &title, const QString &message)
{
    QMessageBox::information(this, title, message);
}

/**
 * @brief 应用设置
 */
void SnakeGameWidget::applySettings()
{
    // === 应用渲染设置 ===
    RenderConfig config = m_gameRenderer->getRenderConfig();

    config.theme = m_themeComboBox->currentText();
    config.cellSize = m_cellSizeSpinBox->value();
    config.enableAnimations = m_animationsCheckBox->isChecked();
    config.enableParticleEffects = m_particlesCheckBox->isChecked();
    config.showGrid = m_gridCheckBox->isChecked();

    // === 设置渲染模式 ===
    QString renderModeText = m_renderModeComboBox->currentText();
    SnakeGameRenderer::RenderMode renderMode = SnakeGameRenderer::Modern;
    if (renderModeText == "Classic") {
        renderMode = SnakeGameRenderer::Classic;
    } else if (renderModeText == "Modern") {
        renderMode = SnakeGameRenderer::Modern;
    } else if (renderModeText == "Minimal") {
        renderMode = SnakeGameRenderer::Minimal;
    } else if (renderModeText == "Retro") {
        renderMode = SnakeGameRenderer::Retro;
    }

    m_gameRenderer->setRenderConfig(config);
    m_gameRenderer->setRenderMode(renderMode);
    m_gameRenderer->setTheme(config.theme);

    // === 保存设置 ===
    saveSettings();
}

/**
 * @brief 加载设置
 */
void SnakeGameWidget::loadSettings()
{
    QSettings settings;

    // === 加载渲染设置 ===
    QString theme = settings.value("render/theme", "default").toString();
    int cellSize = settings.value("render/cellSize", 20).toInt();
    bool animations = settings.value("render/animations", true).toBool();
    bool particles = settings.value("render/particles", true).toBool();
    bool grid = settings.value("render/grid", true).toBool();
    QString renderMode = settings.value("render/mode", "Modern").toString();

    // === 应用到UI控件 ===
    if (m_themeComboBox) {
        int themeIndex = m_themeComboBox->findText(theme);
        if (themeIndex >= 0) {
            m_themeComboBox->setCurrentIndex(themeIndex);
        }
    }

    if (m_cellSizeSpinBox) {
        m_cellSizeSpinBox->setValue(cellSize);
    }

    if (m_animationsCheckBox) {
        m_animationsCheckBox->setChecked(animations);
    }

    if (m_particlesCheckBox) {
        m_particlesCheckBox->setChecked(particles);
    }

    if (m_gridCheckBox) {
        m_gridCheckBox->setChecked(grid);
    }

    if (m_renderModeComboBox) {
        int modeIndex = m_renderModeComboBox->findText(renderMode);
        if (modeIndex >= 0) {
            m_renderModeComboBox->setCurrentIndex(modeIndex);
        }
    }

    // === 应用设置到渲染器 ===
    applySettings();
}

/**
 * @brief 保存设置
 */
void SnakeGameWidget::saveSettings()
{
    QSettings settings;

    // === 保存渲染设置 ===
    if (m_themeComboBox) {
        settings.setValue("render/theme", m_themeComboBox->currentText());
    }

    if (m_cellSizeSpinBox) {
        settings.setValue("render/cellSize", m_cellSizeSpinBox->value());
    }

    if (m_animationsCheckBox) {
        settings.setValue("render/animations", m_animationsCheckBox->isChecked());
    }

    if (m_particlesCheckBox) {
        settings.setValue("render/particles", m_particlesCheckBox->isChecked());
    }

    if (m_gridCheckBox) {
        settings.setValue("render/grid", m_gridCheckBox->isChecked());
    }

    if (m_renderModeComboBox) {
        settings.setValue("render/mode", m_renderModeComboBox->currentText());
    }
}

/**
 * @brief 应用与主界面统一的主题样式
 * 
 * 确保Snake游戏界面与主页面使用一致的颜色方案和样式，
 * 提供统一的用户体验
 */
void SnakeGameWidget::applyUnifiedTheme()
{
    // === 主题颜色配置（与MainWindow保持一致） ===
    QString primaryColor = "#4CAF50";      // 主色调：绿色系（与游戏主题一致）
    QString secondaryColor = "#2196F3";    // 辅助色：蓝色系
    QString backgroundColor = "#1a1a2e";   // 背景色：深色渐变起始色
    QString textColor = "#ffffff";         // 文字色：纯白色
    QString errorColor = "#E74C3C";        // 错误色：红色系
    QString successColor = "#27AE60";      // 成功色：绿色系
    QString warningColor = "#F39C12";      // 警告色：橙色系
    
    // === 应用统一的QSS样式 ===
    QString styleSheet = QString(R"(
        /* SnakeGameWidget主容器样式 */
        SnakeGameWidget {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #1a1a2e, stop:1 #16213e);
            color: %2;
            font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif;
        }
        
        /* 通用组件样式 */
        QWidget {
            background-color: transparent;
            color: %2;
            font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif;
        }
        
        /* 分组框样式 */
        QGroupBox {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 %1, stop:0.5 #34495E, stop:1 #2C3E50);
            border: 2px solid rgba(74, 144, 226, 0.4);
            border-radius: 12px;
            margin: 8px;
            padding-top: 18px;
            font-size: 14px;
            font-weight: bold;
            color: %3;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 15px;
            padding: 0 8px 0 8px;
            color: %3;
            font-size: 15px;
            font-weight: bold;
        }
        
        /* 按钮样式 */
        QPushButton {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.9), stop:1 rgba(52, 73, 94, 0.9));
            color: %2;
            border: 2px solid #34495E;
            border-radius: 8px;
            padding: 10px 16px;
            font-size: 13px;
            font-weight: 500;
            min-width: 80px;
        }
        
        QPushButton:hover {
            border-color: %3;
            color: %3;
        }
        
        QPushButton:pressed {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(74, 144, 226, 0.3), stop:1 rgba(74, 144, 226, 0.2));
        }
        
        QPushButton:disabled {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #7F8C8D, stop:1 #6C7B7D);
            color: #BDC3C7;
            border-color: #7F8C8D;
        }
        
        /* 主要操作按钮样式 */
        QPushButton[class="primary"] {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %3, stop:1 #3498DB);
            color: white;
            border: none;
            font-weight: bold;
        }
        
        QPushButton[class="primary"]:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #5DADE2, stop:1 #4A90E2);
        }
        
        /* 下拉框样式 */
        QComboBox {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.95), stop:1 rgba(52, 73, 94, 0.95));
            border: 2px solid rgba(74, 144, 226, 0.4);
            border-radius: 8px;
            padding: 8px 12px;
            font-size: 13px;
            color: %2;
            font-weight: 500;
            min-width: 100px;
        }
        
        QComboBox:hover {
            border-color: rgba(74, 144, 226, 0.6);
        }
        
        QComboBox:focus {
            border-color: %3;
        }
        
        QComboBox::drop-down {
            border: none;
            background-color: transparent;
            width: 20px;
        }
        
        QComboBox::down-arrow {
            image: none;
            border-left: 5px solid transparent;
            border-right: 5px solid transparent;
            border-top: 5px solid %2;
            margin-right: 8px;
        }
        
        QComboBox QAbstractItemView {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.98), stop:1 rgba(52, 73, 94, 0.98));
            border: 2px solid %3;
            border-radius: 8px;
            color: %2;
            selection-background-color: %3;
            outline: none;
        }
        
        QComboBox QAbstractItemView::item {
            padding: 8px 12px;
            border-bottom: 1px solid rgba(74, 144, 226, 0.2);
        }
        
        QComboBox QAbstractItemView::item:hover {
            background-color: rgba(74, 144, 226, 0.3);
        }
        
        /* 输入框样式 */
        QLineEdit {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.95), stop:1 rgba(52, 73, 94, 0.95));
            border: 2px solid rgba(74, 144, 226, 0.4);
            border-radius: 6px;
            padding: 8px 12px;
            font-size: 13px;
            color: %2;
        }
        
        QLineEdit:hover {
            border-color: rgba(74, 144, 226, 0.6);
        }
        
        QLineEdit:focus {
            border-color: %3;
        }
        
        /* 文本编辑器样式 */
        QTextEdit {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.95), stop:1 rgba(52, 73, 94, 0.95));
            border: 2px solid rgba(74, 144, 226, 0.3);
            border-radius: 8px;
            color: %2;
            font-size: 13px;
            padding: 8px;
        }
        
        QTextEdit:focus {
            border-color: %3;
        }
        
        /* 列表组件样式 */
        QListWidget {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.95), stop:1 rgba(52, 73, 94, 0.95));
            border: 2px solid rgba(74, 144, 226, 0.3);
            border-radius: 8px;
            color: %2;
            font-size: 13px;
            padding: 4px;
        }
        
        QListWidget::item {
            padding: 8px;
            border-bottom: 1px solid rgba(74, 144, 226, 0.2);
            border-radius: 4px;
            margin: 2px;
        }
        
        QListWidget::item:selected {
            background-color: %3;
            color: white;
        }
        
        QListWidget::item:hover {
            background-color: rgba(74, 144, 226, 0.3);
        }
        
        /* 标签样式 */
        QLabel {
            color: %2;
            font-size: 13px;
        }
        
        /* 数字输入框样式 */
        QSpinBox {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.95), stop:1 rgba(52, 73, 94, 0.95));
            border: 2px solid rgba(74, 144, 226, 0.4);
            border-radius: 6px;
            padding: 6px 8px;
            font-size: 13px;
            color: %2;
        }
        
        QSpinBox:hover {
            border-color: rgba(74, 144, 226, 0.6);
        }
        
        QSpinBox:focus {
            border-color: %3;
        }
        
        /* 复选框样式 */
        QCheckBox {
            color: %2;
            font-size: 13px;
            spacing: 8px;
        }
        
        QCheckBox::indicator {
            width: 16px;
            height: 16px;
            border: 2px solid rgba(74, 144, 226, 0.4);
            border-radius: 3px;
            background: rgba(44, 62, 80, 0.8);
        }
        
        QCheckBox::indicator:checked {
            background: %3;
            border-color: %3;
        }
        
        QCheckBox::indicator:hover {
            border-color: rgba(74, 144, 226, 0.6);
        }
        
        /* 分割器样式 */
        QSplitter::handle {
            background-color: rgba(74, 144, 226, 0.4);
            width: 3px;
            border-radius: 1px;
            margin: 2px 0;
        }
        
        QSplitter::handle:hover {
            background-color: rgba(74, 144, 226, 0.7);
        }
        
        /* 滚动条样式 */
        QScrollBar:vertical {
            background-color: rgba(44, 62, 80, 0.8);
            width: 12px;
            border-radius: 6px;
            margin: 0;
        }
        
        QScrollBar::handle:vertical {
            background-color: rgba(74, 144, 226, 0.6);
            border-radius: 6px;
            min-height: 20px;
        }
        
        QScrollBar::handle:vertical:hover {
            background-color: rgba(74, 144, 226, 0.8);
        }
        
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            height: 0;
        }
        
        QScrollBar:horizontal {
            background-color: rgba(44, 62, 80, 0.8);
            height: 12px;
            border-radius: 6px;
            margin: 0;
        }
        
        QScrollBar::handle:horizontal {
            background-color: rgba(74, 144, 226, 0.6);
            border-radius: 6px;
            min-width: 20px;
        }
        
        QScrollBar::handle:horizontal:hover {
            background-color: rgba(74, 144, 226, 0.8);
        }
        
        QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
            width: 0;
        }
        
    )").arg(backgroundColor, textColor, primaryColor);
    
    // === 应用样式到整个组件 ===
    setStyleSheet(styleSheet);
    
    qDebug() << "SnakeGameWidget: Applied unified theme styling";
}

// ===== 单人游戏槽函数实现 =====

/**
 * @brief 单人游戏方向改变槽
 * @param direction 新方向
 */
void SnakeGameWidget::onSinglePlayerDirectionChanged(int direction)
{
    qDebug() << "SnakeGameWidget: 单人游戏方向改变:" << direction;

    // === 发送方向改变消息到游戏服务器 ===
    if (m_gameManager) {
        m_gameManager->changeDirection(direction);
    }
}

/**
 * @brief 单人游戏暂停请求槽
 */
void SnakeGameWidget::onSinglePlayerPauseRequested()
{
    qDebug() << "SnakeGameWidget: 单人游戏暂停请求";

    // === 发送暂停消息到游戏服务器 ===
    // TODO: 实现暂停功能
    qDebug() << "SnakeGameWidget: 暂停功能暂未实现";
    // if (m_gameManager) {
    //     m_gameManager->pauseGame();
    // }
}

/**
 * @brief 单人游戏恢复请求槽
 */
void SnakeGameWidget::onSinglePlayerResumeRequested()
{
    qDebug() << "SnakeGameWidget: 单人游戏恢复请求";

    // === 发送恢复消息到游戏服务器 ===
    // TODO: 实现恢复功能
    qDebug() << "SnakeGameWidget: 恢复功能暂未实现";
    // if (m_gameManager) {
    //     m_gameManager->resumeGame();
    // }
}

/**
 * @brief 单人游戏重新开始请求槽
 */
void SnakeGameWidget::onSinglePlayerRestartRequested()
{
    qDebug() << "SnakeGameWidget: 单人游戏重新开始请求";

    // === 重新创建单人房间 ===
    if (m_gameManager) {
        SnakeGameManager::GameConfig singlePlayerConfig;
        singlePlayerConfig.roomName = "单人练习";
        singlePlayerConfig.maxPlayers = 1;
        singlePlayerConfig.gameMode = 0;                    // SINGLE_PLAYER = 0
        singlePlayerConfig.mapWidth = 40;
        singlePlayerConfig.mapHeight = 30;
        singlePlayerConfig.gameSpeedMs = 100;
        singlePlayerConfig.enableWalls = true;
        singlePlayerConfig.enableSpecialFoods = false;
        singlePlayerConfig.maxFoodCount = 10;

        m_gameManager->createRoom(singlePlayerConfig);
    }
}

/**
 * @brief 单人游戏退出请求槽
 */
void SnakeGameWidget::onSinglePlayerExitRequested()
{
    qDebug() << "SnakeGameWidget: 单人游戏退出请求";

    // === 离开房间 ===
    if (m_gameManager) {
        m_gameManager->leaveRoom();
    }

    // === 发送返回主菜单信号 ===
    emit backToMainMenu();
}

/**
 * @brief 游戏状态更新槽（单人游戏）
 */
void SnakeGameWidget::onGameStateUpdatedForSinglePlayer()
{
    if (!m_singlePlayerWidget || m_currentPage != SinglePlayerPage) {
        return;
    }

    // === 获取游戏状态并转换为单人游戏格式 ===
    SnakeGameState* gameStatePtr = m_gameManager->getGameState();
    if (gameStatePtr) {
        qDebug() << "SnakeGameWidget: 单人游戏状态更新";
        
        // === 从SnakeGameState创建SinglePlayerGameWidget::GameState ===
        SinglePlayerGameWidget::GameState state;
        state.map_size = QSize(gameStatePtr->getBoardWidth(), gameStatePtr->getBoardHeight());
        
        // 状态映射
        switch (gameStatePtr->getGameStatus()) {
            case SnakeGameState::GameStatus::Playing:
                state.status = 1;
                break;
            case SnakeGameState::GameStatus::Paused:
                state.status = 2;
                break;
            case SnakeGameState::GameStatus::Finished:
                state.status = 3;
                break;
            default:
                state.status = 0; // WAITING
                break;
        }
        
        state.tick_count = gameStatePtr->getTickCount();
        state.mode = 0;    // SINGLE_PLAYER
        state.enable_walls = true;
        
        // === 转换蛇数据 ===
        state.snakes.clear();
        const auto& snakes = gameStatePtr->getSnakes();
        for (const auto& snakeData : snakes) {
            SinglePlayerGameWidget::GameState::Snake snake;
            snake.player_id = snakeData.playerId;
            snake.direction = static_cast<int>(snakeData.direction);
            snake.score = snakeData.score;
            snake.is_alive = snakeData.isAlive;
            
            // 转换蛇身位置
            snake.body.clear();
            for (const auto& pos : snakeData.body) {
                snake.body.append(QPoint(pos.x, pos.y));
            }
            
            state.snakes.append(snake);
        }
        
        // === 转换食物数据 ===
        state.foods.clear();
        const auto& foods = gameStatePtr->getFoods();
        for (const auto& foodData : foods) {
            SinglePlayerGameWidget::GameState::Food food;
            food.position = QPoint(foodData.position.x, foodData.position.y);
            food.type = foodData.type == "normal" ? 0 : 1;
            food.value = foodData.value;
            
            state.foods.append(food);
        }

        // === 更新单人游戏组件状态 ===
        m_singlePlayerWidget->updateGameState(state);
        
        qDebug() << "SnakeGameWidget: 状态转换完成 - 蛇数量:" << state.snakes.size() 
                 << "食物数量:" << state.foods.size()
                 << "地图尺寸:" << state.map_size;
    }
}

/**
 * @brief 处理返回大厅按钮点击
 */
void SnakeGameWidget::onBackToLobbyButtonClicked()
{
    qDebug() << "SnakeGameWidget: 返回大厅按钮被点击";

    // === 断开游戏连接 ===
    if (m_gameManager) {
        m_gameManager->disconnectFromGameServer();
    }

    // === 发送返回大厅信号 ===
    emit backToLobbyRequested();
}

/**
 * @brief 处理连接详情按钮点击
 */
void SnakeGameWidget::onConnectionDetailsButtonClicked()
{
    qDebug() << "SnakeGameWidget: 连接详情按钮被点击";

    // === 获取连接详情 ===
    QString details = getWebSocketConnectionDetails();

    // === 显示连接详情对话框 ===
    QMessageBox::information(this, "WebSocket连接详情", details);
}

/**
 * @brief 获取WebSocket连接详情
 */
QString SnakeGameWidget::getWebSocketConnectionDetails()
{
    QString details;

    if (m_gameManager) {
        SnakeGameManager::ConnectionStatus status = m_gameManager->getConnectionStatus();

        details += "=== WebSocket连接详情 ===\n\n";

        // 连接状态
        QString statusText;
        switch (status) {
        case SnakeGameManager::Disconnected:
            statusText = "未连接";
            break;
        case SnakeGameManager::Connecting:
            statusText = "连接中";
            break;
        case SnakeGameManager::Connected:
            statusText = "已连接";
            break;
        case SnakeGameManager::InGame:
            statusText = "游戏中";
            break;
        case SnakeGameManager::Error:
            statusText = "连接错误";
            break;
        }

        details += QString("连接状态: %1\n").arg(statusText);
        details += QString("服务器地址: %1\n").arg("WebSocket服务器");
        details += QString("会话令牌: %1\n").arg("已认证");
        details += QString("玩家ID: %1\n").arg("当前玩家");
        details += QString("玩家名称: %1\n").arg("游戏玩家");

        // 连接时间
        if (status == SnakeGameManager::Connected || status == SnakeGameManager::InGame) {
            details += QString("连接时间: %1\n").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
        }

        details += "\n=== 证明WebSocket长连接成功 ===\n";
        details += "✅ WebSocket协议建立成功\n";
        details += "✅ 心跳包正常发送\n";
        details += "✅ 服务器响应正常\n";
        details += "✅ 实时数据传输正常\n";
    } else {
        details = "游戏管理器未初始化";
    }

    return details;
}

/**
 * @brief 使用WebSocket直接初始化游戏组件（新业务流程）
 * @param websocketUrl WebSocket服务器URL
 * @param gameToken 游戏认证令牌
 * @param playerId 玩家ID
 * @param playerName 玩家名称
 */
void SnakeGameWidget::initializeWithWebSocket(const QString &websocketUrl, const QString &gameToken,
                                             const QString &playerId, const QString &playerName)
{
    qDebug() << "SnakeGameWidget: 使用WebSocket直接初始化游戏组件";
    qDebug() << "  websocketUrl:" << websocketUrl;
    qDebug() << "  gameToken长度:" << gameToken.length();
    qDebug() << "  playerId:" << playerId;
    qDebug() << "  playerName:" << playerName;

    // === 保存连接信息 ===
    m_websocketUrl = websocketUrl;
    m_gameToken = gameToken;
    m_playerId = playerId;
    m_playerName = playerName;

    // === 初始化游戏管理器 ===
    if (!m_gameManager) {
        m_gameManager = new SnakeGameManager(this);

        // === 连接游戏管理器信号 ===
        connect(m_gameManager, &SnakeGameManager::connectionStatusChanged,
                this, &SnakeGameWidget::updateConnectionStatus);
        connect(m_gameManager, &SnakeGameManager::gameStateUpdated,
                this, &SnakeGameWidget::onGameStateUpdatedForSinglePlayer);
        connect(m_gameManager, &SnakeGameManager::roomCreated,
                this, [this](const QString &roomId) {
                    // 创建一个临时的RoomInfo对象
                    SnakeApiClient::RoomInfo roomInfo;
                    roomInfo.roomId = roomId;
                    onRoomCreated(roomInfo);
                });
        connect(m_gameManager, &SnakeGameManager::roomJoined,
                this, &SnakeGameWidget::onRoomJoined);
        connect(m_gameManager, &SnakeGameManager::gameStarted,
                this, &SnakeGameWidget::onGameStarted);
        connect(m_gameManager, &SnakeGameManager::gameEnded,
                this, &SnakeGameWidget::onGameEnded);
        connect(m_gameManager, &SnakeGameManager::playerJoined,
                this, &SnakeGameWidget::onPlayerJoined);
        connect(m_gameManager, &SnakeGameManager::playerLeft,
                this, &SnakeGameWidget::onPlayerLeft);
        connect(m_gameManager, &SnakeGameManager::chatMessageReceived,
                this, &SnakeGameWidget::onChatMessageReceived);
        connect(m_gameManager, &SnakeGameManager::connectionError,
                this, &SnakeGameWidget::onConnectionError);
        connect(m_gameManager, &SnakeGameManager::leaderboardReceived,
                this, &SnakeGameWidget::onLeaderboardReceived);
    }

    // === 直接连接WebSocket并认证 ===
    connectToWebSocketAndAuthenticate();
}

/**
 * @brief 连接WebSocket并进行认证
 */
void SnakeGameWidget::connectToWebSocketAndAuthenticate()
{
    qDebug() << "SnakeGameWidget: 开始连接WebSocket并认证";

    // === 使用SnakeGameManager连接WebSocket ===
    if (m_gameManager) {
        // === 构建WebSocket连接配置 ===
        SnakeGameManager::WebSocketConfig config;
        config.url = m_websocketUrl;
        config.gameToken = m_gameToken;
        config.playerId = m_playerId;
        config.playerName = m_playerName;
        config.clientType = "qt6";
        config.protocolVersion = "1.0";
        config.heartbeatInterval = 30000;  // 30秒心跳
        config.autoReconnect = true;
        config.maxReconnectAttempts = 5;

        // === 开始连接 ===
        bool success = m_gameManager->connectToWebSocket(config);
        if (success) {
            qDebug() << "SnakeGameWidget: WebSocket连接请求已发送";
            updateConnectionStatus();
        } else {
            qDebug() << "SnakeGameWidget: WebSocket连接请求失败";
            QMessageBox::warning(this, "连接失败", "无法连接到游戏服务器，请检查网络连接。");
        }
    } else {
        qDebug() << "SnakeGameWidget: 游戏管理器未初始化";
        QMessageBox::critical(this, "初始化错误", "游戏管理器未正确初始化。");
    }
}

/**
 * @brief 处理连接错误
 * @param error 错误信息
 */
void SnakeGameWidget::onConnectionError(const QString &error)
{
    qWarning() << "SnakeGameWidget: 连接错误:" << error;

    // === 更新连接状态 ===
    updateConnectionStatus();

    // === 显示错误提示 ===
    QMessageBox::warning(this, "连接错误", QString("WebSocket连接出现错误：\n%1").arg(error));
}
